import sys
import json
import os
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                              QHBoxLayout, QPushButton, QLabel, QLineEdit, 
                              QTextEdit, QComboBox, QScrollArea, QFrame, QGridLayout,
                              QStatusBar, QMenu, QFileDialog, QInputDialog,
                              QMessageBox, QSplitter, QSpacerItem, QSizePolicy)
from PySide6.QtCore import Qt, QSize, Signal, Slot, QPoint, QMimeData
from PySide6.QtGui import (QFont, QColor, QPalette, QIcon, QDrag, QPainter, 
                           QPen, QBrush, QActionGroup, QAction)

class CardWidget(QFrame):
    """卡片组件类，每个卡片包含关闭按钮和自定义组件"""
    
    # 定义信号
    card_removed = Signal(object)
    card_moved = Signal(object, int)
    card_renamed = Signal(object, str)
    card_selected = Signal(object)
    
    def __init__(self, parent=None, title="卡片", card_id=None):
        super().__init__(parent)
        self.parent = parent
        self.title = title
        self.card_id = card_id or id(self)  # 唯一标识
        self.is_selected = False
        
        # 设置卡片样式
        self.setStyleSheet("""
            CardWidget {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #e0e0e0;
                margin: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                transition: all 0.3s ease;
            }
            CardWidget:hover {
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
        """)
        self.setMinimumHeight(240)
        self.setMaximumWidth(320)
        self.setMinimumWidth(280)
        self.setAcceptDrops(True)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(12, 12, 12, 12)
        main_layout.setSpacing(10)
        
        # 标题栏布局
        title_layout = QHBoxLayout()
        
        # 标题标签
        self.title_label = QLabel(title)
        font = QFont()
        font.setBold(True)
        font.setPointSize(11)
        self.title_label.setFont(font)
        self.title_label.setStyleSheet("color: #2c3e50;")
        title_layout.addWidget(self.title_label)
        
        # 关闭按钮
        self.close_btn = QPushButton("×")
        self.close_btn.setStyleSheet("""
            QPushButton {
                color: #e74c3c;
                background-color: transparent;
                border: none;
                font-size: 16px;
                font-weight: bold;
                width: 24px;
                height: 24px;
                border-radius: 12px;
            }
            QPushButton:hover {
                background-color: #f8f9fa;
            }
            QPushButton:pressed {
                background-color: #e9ecef;
            }
        """)
        self.close_btn.clicked.connect(self.remove_card)
        title_layout.addWidget(self.close_btn, alignment=Qt.AlignRight)
        
        main_layout.addLayout(title_layout)
        
        # 添加自定义组件
        self.add_custom_components(main_layout)
        
        # 允许右键菜单
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)
        
        # 鼠标事件用于拖拽
        self.dragging = False
        self.drag_start_position = QPoint()
        
    def add_custom_components(self, parent_layout):
        """添加自定义组件到卡片"""
        # 使用网格布局排列自定义组件
        grid_layout = QGridLayout()
        grid_layout.setSpacing(8)
        
        # 证件类型选择
        type_label = QLabel("证件类型:")
        type_label.setStyleSheet("color: #34495e; font-size: 12px;")
        self.type_combo = QComboBox()
        self.type_combo.addItems(["身份证", "护照", "驾驶证", "工作证", "其他"])
        self.type_combo.setMinimumHeight(28)
        self.type_combo.setStyleSheet("""
            QComboBox {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 5px;
                background-color: white;
            }
            QComboBox:hover {
                border-color: #3498db;
            }
        """)
        grid_layout.addWidget(type_label, 0, 0)
        grid_layout.addWidget(self.type_combo, 0, 1)
        
        # 证件号码输入
        num_label = QLabel("证件号码:")
        num_label.setStyleSheet("color: #34495e; font-size: 12px;")
        self.num_edit = QLineEdit()
        self.num_edit.setMinimumHeight(28)
        self.num_edit.setStyleSheet("""
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 5px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #f8f9ff;
            }
        """)
        grid_layout.addWidget(num_label, 1, 0)
        grid_layout.addWidget(self.num_edit, 1, 1)
        
        # 持有人输入
        holder_label = QLabel("持有人:")
        holder_label.setStyleSheet("color: #34495e; font-size: 12px;")
        self.holder_edit = QLineEdit()
        self.holder_edit.setMinimumHeight(28)
        self.holder_edit.setStyleSheet("""
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 5px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #f8f9ff;
            }
        """)
        grid_layout.addWidget(holder_label, 2, 0)
        grid_layout.addWidget(self.holder_edit, 2, 1)
        
        # 备注信息
        note_label = QLabel("备注信息:")
        note_label.setStyleSheet("color: #34495e; font-size: 12px;")
        self.note_edit = QTextEdit()
        self.note_edit.setMaximumHeight(60)
        self.note_edit.setMinimumHeight(60)
        self.note_edit.setStyleSheet("""
            QTextEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 5px;
            }
            QTextEdit:focus {
                border-color: #3498db;
                background-color: #f8f9ff;
            }
        """)
        grid_layout.addWidget(note_label, 3, 0)
        grid_layout.addWidget(self.note_edit, 3, 1)
        
        parent_layout.addLayout(grid_layout)
        
        # 添加伸缩项，使内容顶部对齐
        parent_layout.addStretch()
        
    def remove_card(self):
        """从父容器中移除当前卡片"""
        # 发送移除信号
        self.card_removed.emit(self)
        
        # 添加淡出动画效果
        self.setStyleSheet("""
            CardWidget {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #e0e0e0;
                margin: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                opacity: 0;
                transform: translateY(10px) scale(0.95);
                transition: all 0.3s ease-out;
            }
        """)
        
        # 延迟删除以显示动画
        QApplication.processEvents()
        self.deleteLater()
    
    def get_card_data(self):
        """获取卡片中的数据"""
        return {
            "id": self.card_id,
            "title": self.title,
            "type": self.type_combo.currentText(),
            "number": self.num_edit.text(),
            "holder": self.holder_edit.text(),
            "note": self.note_edit.toPlainText()
        }
    
    def set_card_data(self, data):
        """设置卡片数据"""
        if "title" in data:
            self.title = data["title"]
            self.title_label.setText(self.title)
        if "type" in data:
            index = self.type_combo.findText(data["type"])
            if index >= 0:
                self.type_combo.setCurrentIndex(index)
        if "number" in data:
            self.num_edit.setText(data["number"])
        if "holder" in data:
            self.holder_edit.setText(data["holder"])
        if "note" in data:
            self.note_edit.setPlainText(data["note"])
        if "id" in data:
            self.card_id = data["id"]
    
    def mousePressEvent(self, event):
        """鼠标按下事件，用于拖拽和选中"""
        if event.button() == Qt.LeftButton:
            self.drag_start_position = event.pos()
            # 选中卡片
            self.select_card(True)
            self.card_selected.emit(self)
        super().mousePressEvent(event)
    
    def mouseMoveEvent(self, event):
        """鼠标移动事件，处理拖拽"""
        if not (event.buttons() & Qt.LeftButton):
            return
            
        # 检查拖拽距离是否足够
        if (event.pos() - self.drag_start_position).manhattanLength() < QApplication.startDragDistance():
            return
            
        self.dragging = True
        drag = QDrag(self)
        mime_data = QMimeData()
        
        # 存储卡片ID用于拖拽识别
        mime_data.setText(str(self.card_id))
        drag.setMimeData(mime_data)
        
        # 拖拽时的视觉效果
        pixmap = self.grab()
        drag.setPixmap(pixmap.scaled(0.8 * pixmap.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
        drag.setHotSpot(QPoint(20, 20))
        
        drag.exec_(Qt.MoveAction)
        self.dragging = False
    
    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        if self.dragging:
            self.dragging = False
        super().mouseReleaseEvent(event)
    
    def dragEnterEvent(self, event):
        """拖拽进入事件"""
        if event.mimeData().hasText() and event.mimeData().text() != str(self.card_id):
            event.acceptProposedAction()
    
    def dropEvent(self, event):
        """放置事件"""
        if event.mimeData().hasText():
            source_id = int(event.mimeData().text())
            # 找到源卡片
            for card in self.parent.cards:
                if card.card_id == source_id:
                    # 发送移动信号
                    current_index = self.parent.cards.index(self)
                    self.card_moved.emit(card, current_index)
                    break
            event.acceptProposedAction()
    
    def show_context_menu(self, position):
        """显示右键菜单"""
        menu = QMenu()
        
        # 重命名动作
        rename_action = QAction("重命名卡片", self)
        rename_action.triggered.connect(self.rename_card)
        
        # 复制动作
        copy_action = QAction("复制卡片", self)
        copy_action.triggered.connect(self.copy_card)
        
        # 删除动作
        delete_action = QAction("删除卡片", self)
        delete_action.triggered.connect(self.remove_card)
        delete_action.setIconVisibleInMenu(False)
        
        menu.addAction(rename_action)
        menu.addAction(copy_action)
        menu.addSeparator()
        menu.addAction(delete_action)
        
        # 显示菜单
        menu.exec_(self.mapToGlobal(position))
    
    def rename_card(self):
        """重命名卡片"""
        new_title, ok = QInputDialog.getText(self, "重命名卡片", "请输入新名称:", text=self.title)
        if ok and new_title:
            self.title = new_title
            self.title_label.setText(new_title)
            self.card_renamed.emit(self, new_title)
    
    def copy_card(self):
        """复制卡片"""
        if hasattr(self.parent, 'copy_card'):
            self.parent.copy_card(self)
    
    def select_card(self, selected):
        """设置卡片选中状态"""
        self.is_selected = selected
        if selected:
            self.setStyleSheet("""
                CardWidget {
                    background-color: #f0f7ff;
                    border-radius: 8px;
                    border: 2px solid #3498db;
                    margin: 8px;
                    box-shadow: 0 4px 12px rgba(52, 152, 219, 0.2);
                    transition: all 0.2s ease;
                }
            """)
        else:
            self.setStyleSheet("""
                CardWidget {
                    background-color: white;
                    border-radius: 8px;
                    border: 1px solid #e0e0e0;
                    margin: 8px;
                    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                    transition: all 0.3s ease;
                }
                CardWidget:hover {
                    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
                }
            """)


class CardListApp(QWidget):
    """主应用窗口，包含卡片列表和添加卡片按钮"""
    
    def __init__(self):
        super().__init__()
        self.setWindowTitle("证件卡片管理系统")
        self.setGeometry(100, 100, 1100, 650)
        
        # 设置中文字体
        font = QFont()
        font.setFamily("SimHei")  # 使用黑体显示中文
        font.setPointSize(10)
        self.setFont(font)
        
        # 创建中心部件
        # central_widget = QWidget(self)
        # self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(12)
        
        # 顶部布局：标题和操作按钮
        top_layout = QHBoxLayout()
        
        # 标题
        title_label = QLabel("证件卡片列表")
        title_font = QFont()
        title_font.setFamily("SimHei")
        title_font.setBold(True)
        title_font.setPointSize(16)
        title_label.setFont(title_font)
        title_label.setStyleSheet("color: #2c3e50;")
        top_layout.addWidget(title_label)
        
        # 添加伸缩项，将按钮推到右侧
        top_layout.addStretch()
        
        # 操作按钮区域
        button_layout = QHBoxLayout()
        button_layout.setSpacing(8)
        
        # 导入按钮
        self.import_btn = QPushButton("导入卡片")
        self.import_btn.setStyleSheet(self.get_button_style())
        self.import_btn.clicked.connect(self.import_cards)
        button_layout.addWidget(self.import_btn)
        
        # 导出按钮
        self.export_btn = QPushButton("导出卡片")
        self.export_btn.setStyleSheet(self.get_button_style())
        self.export_btn.clicked.connect(self.export_cards)
        button_layout.addWidget(self.export_btn)
        
        # 添加卡片按钮
        self.add_btn = QPushButton("添加新卡片")
        self.add_btn.setStyleSheet("""
            QPushButton {
                background-color: #3498db;
                color: white;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 14px;
                border: none;
                min-width: 120px;
                min-height: 36px;
            }
            QPushButton:hover {
                background-color: #2980b9;
            }
            QPushButton:pressed {
                background-color: #2471a3;
            }
        """)
        self.add_btn.clicked.connect(self.add_card)
        button_layout.addWidget(self.add_btn)
        
        top_layout.addLayout(button_layout)
        
        main_layout.addLayout(top_layout)
        
        # 搜索框
        search_layout = QHBoxLayout()
        search_label = QLabel("搜索:")
        search_label.setStyleSheet("color: #34495e; font-weight: bold;")
        self.search_edit = QLineEdit()
        self.search_edit.setPlaceholderText("输入关键词搜索卡片内容...")
        self.search_edit.setMinimumHeight(32)
        self.search_edit.textChanged.connect(self.filter_cards)
        self.search_edit.setStyleSheet("""
            QLineEdit {
                border: 1px solid #bdc3c7;
                border-radius: 4px;
                padding: 5px 10px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: #f8f9ff;
            }
        """)
        search_layout.addWidget(search_label)
        search_layout.addWidget(self.search_edit)
        main_layout.addLayout(search_layout)
        
        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        scroll_area.setStyleSheet("""
            QScrollArea {
                border: 1px solid #e0e0e0;
                background-color: #f8f9fa;
                border-radius: 8px;
            }
            QScrollBar:vertical {
                border: none;
                background: #f1f1f1;
                width: 8px;
                margin: 0px;
                border-radius: 4px;
            }
            QScrollBar::handle:vertical {
                background: #bdc3c7;
                border-radius: 4px;
            }
            QScrollBar::handle:vertical:hover {
                background: #95a5a6;
            }
            QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
                height: 0px;
            }
        """)
        
        # 滚动区域的内容部件
        self.scroll_content = QWidget()
        self.scroll_content.setStyleSheet("background-color: #f8f9fa;")
        scroll_area.setWidget(self.scroll_content)
        
        # 卡片布局（使用QHBoxLayout水平排列卡片，自动换行）
        # self.cards_layout = QHBoxLayout(self.scroll_content)
        self.cards_layout = QVBoxLayout(self.scroll_content)
        self.cards_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.cards_layout.setSpacing(12)
        
        # 添加空状态显示
        self.empty_state = QWidget()
        empty_layout = QVBoxLayout(self.empty_state)
        empty_layout.setAlignment(Qt.AlignCenter)
        empty_layout.setContentsMargins(0, 50, 0, 50)
        
        empty_icon = QLabel()
        empty_icon.setText("📁")
        empty_icon.setStyleSheet("font-size: 48px; margin-bottom: 15px;")
        empty_icon.setAlignment(Qt.AlignCenter)
        
        empty_label = QLabel("暂无卡片数据")
        empty_label.setStyleSheet("font-size: 16px; color: #7f8c8d; margin-bottom: 10px;")
        empty_label.setAlignment(Qt.AlignCenter)
        
        empty_desc = QLabel("点击下方按钮添加新卡片或导入已有卡片")
        empty_desc.setStyleSheet("font-size: 12px; color: #95a5a6; margin-bottom: 20px;")
        empty_desc.setAlignment(Qt.AlignCenter)
        
        empty_add_btn = QPushButton("添加新卡片")
        empty_add_btn.setStyleSheet(self.get_button_style("primary"))
        empty_add_btn.clicked.connect(self.add_card)
        
        empty_layout.addWidget(empty_icon)
        empty_layout.addWidget(empty_label)
        empty_layout.addWidget(empty_desc)
        empty_layout.addWidget(empty_add_btn)
        
        self.cards_layout.addWidget(self.empty_state)
        
        main_layout.addWidget(scroll_area)
        
        # 状态栏
        self.statusBar = QStatusBar()
        # self.setStatusBar(self.statusBar)
        self.statusBar.showMessage("就绪 - 0张卡片")
        
        # 存储所有卡片的列表
        self.cards = []
        self.filter_text = ""
        
        # 初始添加几张卡片
        self.add_card("身份证卡片")
        self.add_card("护照信息")
        self.add_card("驾驶证信息")
        
        # 设置快捷键
        self.setup_shortcuts()
    
    def get_button_style(self, type="default"):
        """获取按钮样式"""
        if type == "primary":
            return """
                QPushButton {
                    background-color: #3498db;
                    color: white;
                    padding: 6px 12px;
                    border-radius: 4px;
                    font-size: 13px;
                    border: none;
                    min-height: 32px;
                }
                QPushButton:hover {
                    background-color: #2980b9;
                }
                QPushButton:pressed {
                    background-color: #2471a3;
                }
                QPushButton:disabled {
                    background-color: #bdc3c7;
                    color: #ecf0f1;
                }
            """
        return """
            QPushButton {
                background-color: #ecf0f1;
                color: #2c3e50;
                padding: 6px 12px;
                border-radius: 4px;
                font-size: 13px;
                border: 1px solid #bdc3c7;
                min-height: 32px;
            }
            QPushButton:hover {
                background-color: #d5dbdb;
            }
            QPushButton:pressed {
                background-color: #b3b6b7;
            }
            QPushButton:disabled {
                background-color: #f1f2f6;
                color: #b2babb;
                border-color: #d6dbdf;
            }
        """
    
    def setup_shortcuts(self):
        """设置快捷键"""
        # 添加卡片 Ctrl+N
        add_action = QAction("添加卡片", self)
        add_action.setShortcut("Ctrl+N")
        add_action.triggered.connect(self.add_card)
        self.addAction(add_action)
        
        # 导入卡片 Ctrl+I
        import_action = QAction("导入卡片", self)
        import_action.setShortcut("Ctrl+I")
        import_action.triggered.connect(self.import_cards)
        self.addAction(import_action)
        
        # 导出卡片 Ctrl+E
        export_action = QAction("导出卡片", self)
        export_action.setShortcut("Ctrl+E")
        export_action.triggered.connect(self.export_cards)
        self.addAction(export_action)
        
        # 删除选中卡片 Delete
        delete_action = QAction("删除卡片", self)
        delete_action.setShortcut(Qt.Key_Delete)
        delete_action.triggered.connect(self.delete_selected_card)
        self.addAction(delete_action)
    
    def add_card(self, title=None):
        """添加新卡片到列表"""
        # 隐藏空状态
        if self.empty_state.isVisible():
            self.empty_state.hide()
        
        if not title:
            # 如果没有指定标题，自动生成一个
            card_count = len(self.cards)
            title = f"证件卡片 {card_count + 1}"
        
        # 创建新卡片
        card = CardWidget(self, title)
        card.card_removed.connect(self.remove_card)
        card.card_moved.connect(self.move_card)
        card.card_selected.connect(self.on_card_selected)
        self.cards.append(card)
        self.cards_layout.addWidget(card)
        
        # 更新状态栏
        self.update_status_bar()
        
        # 添加淡入动画效果
        card.setStyleSheet("""
            CardWidget {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #e0e0e0;
                margin: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                opacity: 0;
                transform: translateY(10px);
                transition: all 0.3s ease-out;
            }
        """)
        
        # 强制刷新
        QApplication.processEvents()
        
        # 应用最终样式
        card.setStyleSheet("""
            CardWidget {
                background-color: white;
                border-radius: 8px;
                border: 1px solid #e0e0e0;
                margin: 8px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
                opacity: 1;
                transform: translateY(0);
                transition: all 0.3s ease;
            }
            CardWidget:hover {
                box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            }
        """)
        
        return card
    
    def remove_card(self, card):
        """从布局中移除卡片"""
        if card in self.cards:
            self.cards.remove(card)
        self.cards_layout.removeWidget(card)
        
        # 如果没有卡片了，显示空状态
        if len(self.cards) == 0:
            self.empty_state.show()
        
        # 更新状态栏
        self.update_status_bar()
    
    def move_card(self, card, target_index):
        """移动卡片到指定位置"""
        if card not in self.cards:
            return
            
        current_index = self.cards.index(card)
        
        # 调整列表顺序
        if current_index < target_index:
            # 向后移动
            self.cards.insert(target_index + 1, self.cards.pop(current_index))
        else:
            # 向前移动
            self.cards.insert(target_index, self.cards.pop(current_index))
        
        # 重新排列布局中的卡片
        self.rearrange_cards()
    
    def rearrange_cards(self):
        """重新排列布局中的卡片"""
        # 清除所有卡片
        while self.cards_layout.count():
            item = self.cards_layout.takeAt(0)
            if item.widget():
                item.widget().setParent(None)
        
        # 重新添加卡片（保持空状态在最后）
        for card in self.cards:
            self.cards_layout.addWidget(card)
        
        if len(self.cards) == 0:
            self.cards_layout.addWidget(self.empty_state)
            self.empty_state.show()
    
    def copy_card(self, original_card):
        """复制卡片"""
        card_data = original_card.get_card_data()
        new_card = self.add_card(f"{card_data['title']} (副本)")
        new_card.set_card_data(card_data)
        new_card.card_id = id(new_card)  # 确保新ID唯一
    
    def on_card_selected(self, selected_card):
        """处理卡片选中事件"""
        # 取消其他卡片的选中状态
        for card in self.cards:
            if card != selected_card:
                card.select_card(False)
        
        # 状态栏显示信息
        self.statusBar.showMessage(f"选中: {selected_card.title}")
    
    def delete_selected_card(self):
        """删除选中的卡片"""
        selected_cards = [card for card in self.cards if card.is_selected]
        if not selected_cards:
            self.statusBar.showMessage("请先选中要删除的卡片")
            return
            
        # 确认删除
        card = selected_cards[0]
        reply = QMessageBox.question(
            self, 
            "确认删除", 
            f"确定要删除卡片「{card.title}」吗？",
            QMessageBox.Yes | QMessageBox.No, 
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            card.remove_card()
    
    def filter_cards(self, text):
        """根据文本过滤卡片"""
        self.filter_text = text.lower()
        
        if not self.filter_text:
            # 没有过滤文本，显示所有卡片
            for card in self.cards:
                card.setVisible(True)
            self.statusBar.showMessage(f"就绪 - {len(self.cards)}张卡片")
            return
        
        # 过滤卡片
        visible_count = 0
        for card in self.cards:
            data = card.get_card_data()
            # 检查所有字段是否包含过滤文本
            match = (self.filter_text in data["title"].lower() or
                    self.filter_text in data["type"].lower() or
                    self.filter_text in data["number"].lower() or
                    self.filter_text in data["holder"].lower() or
                    self.filter_text in data["note"].lower())
            
            card.setVisible(match)
            if match:
                visible_count += 1
        
        self.statusBar.showMessage(f"搜索结果: {visible_count}张卡片 (共{len(self.cards)}张)")
    
    def export_cards(self):
        """导出卡片数据到JSON文件"""
        if not self.cards:
            QMessageBox.information(self, "提示", "没有可导出的卡片数据")
            return
            
        # 获取保存路径
        file_path, _ = QFileDialog.getSaveFileName(
            self, "导出卡片数据", "", "JSON文件 (*.json);;所有文件 (*)"
        )
        
        if not file_path:
            return
            
        # 确保文件有.json扩展名
        if not file_path.endswith(".json"):
            file_path += ".json"
        
        # 收集卡片数据
        cards_data = [card.get_card_data() for card in self.cards]
        
        try:
            # 保存到文件
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(cards_data, f, ensure_ascii=False, indent=2)
            
            self.statusBar.showMessage(f"成功导出 {len(self.cards)} 张卡片到 {file_path}")
            QMessageBox.information(self, "成功", f"已成功导出 {len(self.cards)} 张卡片")
        except Exception as e:
            self.statusBar.showMessage(f"导出失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"导出失败: {str(e)}")
    
    def import_cards(self):
        """从JSON文件导入卡片数据"""
        # 获取文件路径
        file_path, _ = QFileDialog.getOpenFileName(
            self, "导入卡片数据", "", "JSON文件 (*.json);;所有文件 (*)"
        )
        
        if not file_path:
            return
            
        try:
            # 读取文件
            with open(file_path, 'r', encoding='utf-8') as f:
                cards_data = json.load(f)
            
            # 导入卡片
            imported_count = 0
            for data in cards_data:
                new_card = self.add_card()
                new_card.set_card_data(data)
                imported_count += 1
            
            self.statusBar.showMessage(f"成功从 {file_path} 导入 {imported_count} 张卡片")
            QMessageBox.information(self, "成功", f"已成功导入 {imported_count} 张卡片")
        except Exception as e:
            self.statusBar.showMessage(f"导入失败: {str(e)}")
            QMessageBox.critical(self, "错误", f"导入失败: {str(e)}")
    
    def update_status_bar(self):
        """更新状态栏信息"""
        card_count = len(self.cards)
        if card_count == 0:
            self.statusBar.showMessage("就绪 - 暂无卡片")
        elif card_count == 1:
            self.statusBar.showMessage("就绪 - 1张卡片")
        else:
            self.statusBar.showMessage(f"就绪 - {card_count}张卡片")
    
    def resizeEvent(self, event):
        """窗口大小改变事件"""
        # 调整卡片布局，确保良好的显示效果
        super().resizeEvent(event)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    
    # 设置全局样式
    app.setStyle("Fusion")  # 使用Fusion风格，跨平台一致性更好
    
    # 设置全局调色板
    palette = QPalette()
    palette.setColor(QPalette.Window, QColor(248, 249, 250))
    palette.setColor(QPalette.WindowText, QColor(33, 37, 41))
    palette.setColor(QPalette.Base, QColor(255, 255, 255))
    palette.setColor(QPalette.AlternateBase, QColor(248, 249, 250))
    palette.setColor(QPalette.ToolTipBase, QColor(255, 255, 255))
    palette.setColor(QPalette.ToolTipText, QColor(33, 37, 41))
    palette.setColor(QPalette.Text, QColor(33, 37, 41))
    palette.setColor(QPalette.Button, QColor(248, 249, 250))
    palette.setColor(QPalette.ButtonText, QColor(33, 37, 41))
    palette.setColor(QPalette.BrightText, QColor(255, 0, 0))
    palette.setColor(QPalette.Link, QColor(52, 152, 219))
    palette.setColor(QPalette.Highlight, QColor(52, 152, 219))
    palette.setColor(QPalette.HighlightedText, QColor(255, 255, 255))
    app.setPalette(palette)
    
    window = CardListApp()
    window.show()
    sys.exit(app.exec())
    